package com.cxl.price.service;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.springframework.stereotype.Service;

import com.cxl.parser.GrabTaoBao;
import com.cxl.parser.InfoGrab;
import com.cxl.parser.ShopFactory;
import com.cxl.parser.grab.GrabCommon;
import com.cxl.price.bean.Good;
import com.cxl.price.bean.Goods;
import com.cxl.price.bean.Imgs;
import com.cxl.price.bean.Shop;
import com.cxl.price.dao.GoodDao;
import com.cxl.price.dao.GoodsDao;
import com.cxl.price.top.service.TopBaseService;
import com.cxl.price.top.service.TopItemResponseService;
import com.cxl.price.top.service.TopProductService;
import com.cxl.price.util.RegexpGood;
import com.summer.core.service.impl.BaseServiceImpl;
import com.summer.core.util.StringUtil;
import com.taobao.api.ApiException;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.ItemImg;
import com.taobao.api.request.ProductGetRequest;
import com.taobao.api.request.ProductsSearchRequest;

@Service
public class GoodsServiceImpl extends BaseServiceImpl<Goods, String, GoodsDao>
		implements GoodsService {

	
	private TopBaseService topBaseService;
	@Resource
	public void setTopBaseService(TopBaseService topBaseService) {
		this.topBaseService = topBaseService;
	}
	@Resource
	public void setDao(GoodsDao dao) {
		this.dao = dao;
	}
	
	
	private GoodDao goodDao=null;
	
	public GoodDao getGoodDao() {
		return goodDao;
	}
	@Resource
	public void setGoodDao(GoodDao goodDao) {
		this.goodDao = goodDao;
	}
	
	

	
	
	/**
	 * 判断老的是否还可以用  可以用酒用 不可以用酒曲搜索
	 */
	
	/**
	 * 查看名称是否包含 搜索关键字
	 * @param good 原先商店  原先关联地址是否包含搜索关键字  true关联 false不关联 要删除
	 * @return
	 * @throws ParserException 
	 */
	public boolean saveDoSearch(GrabCommon grab,Good good,Goods goods,Shop shop) throws ParserException
	{
		grab.setUrl(good.getUrl());
		String title=grab.getTitle();
		title=StringUtil.ToDBC(title);
//		if(StringUtils.contains(title,)&&StringUtils.contains(StringUtil.ToDBC(title),goods.getXinghao()))
//		{
		RegexpGood xp=new RegexpGood(goods.getPinpai(), goods.getXinghao(), title);
		//System.out.println();
		if(xp.comp())
		{
			if(good.getId()==null)
			{
			good.setGoods(goods);
			}
			good.setShop(shop);
		//	good.setPic_url(grab.getImgHref());
			good.setPrice(grab.getPrice());
			String pic_url=grab.getImgHref()+";";
			for(String url: grab.getOtherImgsHref())
			{
				if(pic_url.indexOf(url)==-1)
					pic_url+=url+";";
			}
			good.setPic_url(pic_url);
			goodDao.saveOrupdate(good);
			return true;
		}
		else
		{
			goods.removeGood(good);
			goodDao.delete(good);
			
		
		//	update(goods);
		}
		return false;
	}
	
	
	//更新所有的url
	public void addSearchAllShopAndImport(List<Shop> shopList,List<Goods> goodsList) throws Exception
	{
		for(Shop shop:shopList)//搜索的商店
		{
			GrabCommon grab=null;
			grab=(GrabCommon) Class.forName(shop.getGrabClassPath()).newInstance();
			//int j=0;
			for(Goods goods:goodsList)
			{
				addOne(goods,shop,grab);
				
			}
		}
	}
	
	
	public void addOne(Goods goods,Shop shop,GrabCommon grab) throws Exception
	{
		Good good=null;
		String url=shop.getSearchKey();
		//System.out.println("-------【"+shop.getCnName()+"】匹配商品【"+goods.getName()+"】-------序列号【"+j+"】编码["+goods.getId()+"]目前匹配good数量："+goods.getGood().size());
		if(goods.isMatchGood()==false) //可以匹配才匹配
		{
		Set<Good> goodSet=goods.getGood();
		Iterator<Good> iterator=goodSet.iterator();
		boolean flag=true;
	//匹配以前的 
		while(iterator.hasNext())
		{
			good=iterator.next();
			if(good.getShop().id.equals(shop.getId()))
			{
				if(saveDoSearch(grab, good,goods, shop))
				{
					flag=false;
					
				}
				
				break;
			}
		}
		//以前没有 或者有却不关联 则重新匹配
		String search=goods.getPinpai()+" "+(StringUtils.isNotEmpty(goods.getXinghao())?goods.getXinghao():"");
		if((StringUtils.isNotEmpty(goods.getPinpai())||StringUtils.isNotEmpty(goods.getXinghao()))&&flag)
		{
			String searchurl=url+java.net.URLEncoder.encode(search,shop.getEncode());
			grab.setUrl(searchurl);
			NodeList htmlNodelist=grab.getNodeListHtml(searchurl);
			
			List<Good> list=grab.searchGoodsUrl(htmlNodelist);
			int i=0;
			while(list.size()>i&&flag==true&&i<2)
			{
				
				good=new Good();
				good.setUrl(list.get(i).getUrl());
				flag=!saveDoSearch(grab, good,goods, shop);
				i++;
			}
			
		}}
		
		update(goods);
	
	
		
		
	}
	
	public void addSearchAllShopAndImport(List<Shop> shopList,Goods goods) throws Exception
	{
		
		for(Shop shop:shopList)
		{
			GrabCommon grab=null;
			grab=(GrabCommon) Class.forName(shop.getGrabClassPath()).newInstance();
			addOne(goods,shop,grab);
		}
	}

/**
 * 导入淘宝商店已上架商品
 * @throws Exception 
 */
	
	public void addTaoBaoGoods(List<Item> items,HttpServletRequest req) throws Exception
	{
		TopProductService tps=new TopProductService();
		TopItemResponseService topItemResponseService=new TopItemResponseService();
		
		ProductGetRequest request=new ProductGetRequest();
		ProductsSearchRequest request2=new ProductsSearchRequest();
		for(Item item:items)
		{
//			String urltemp=item.getDetailUrl();
			Goods goods=null;
			if(dao.get("num_iid", item.getNumIid())!=null)
			goods=dao.get("num_iid",item.getNumIid());
				else
				{
					goods=new Goods();
					goods.setNum_iid(item.getNumIid());
				}
			
			String title=item.getTitle();
			goods.setName(title);
			goods.setCreateDate(item.getListTime());
			goods.setTb_url(item.getDetailUrl());
			goods.setTb_img(item.getPicUrl());
			goods.setSeller_cids(item.getSellerCids());
			goods.setOnSale(item.getApproveStatus());
			goods.setPrice(Double.parseDouble(item.getPrice()));
			goods.setSynch(true);
			goods.setHasShowcase(item.getHasShowcase());
		
			
			if(title.indexOf("[")!=-1)
			{
			String px=title.substring(title.indexOf("[")+1,title.indexOf("]"));
			if(px.indexOf(" ")!=-1)
			{
			goods.setPinpai(px.split(" ")[0]);
			goods.setXinghao(px.split(" ")[1]);
			}
			else
			goods.setPinpai(px);
			}
			else
			{
				//没有按照[]录入宝贝名称的 则按照 宝贝的淘宝属性去找他的
				Item itemDetail=topBaseService.getTaobaoResponse(topItemResponseService.getItemGetRequest(item.getNumIid()),req).getItem();
				goods.setProduct_id(itemDetail.getProductId());
				
				String propsName[]=itemDetail.getPropsName().split(";");
				String total="";
				for(String pr:propsName)
				{
					String cc[]=pr.split(":");
					if(cc.length==4)
					{
						total+=cc[2]+":"+cc[3]+";";
						
						if(cc[2].equals("品牌"))
						{
							goods.setPinpai(cc[3]);
						}
						if(cc[2].equals("型号"))
						{
							goods.setXinghao(cc[3]);
						}
					}
					
				}
				goods.setPropsName(total);
			//	goods.setVolume(itemDetail.getVolume());
				goods.setNum(itemDetail.getNum());
				goods.setDescription(itemDetail.getDesc());
				goods.setTb_url(itemDetail.getDetailUrl());
				List<ItemImg> imgs=itemDetail.getItemImgs();
				//myImg.set
				Set<Imgs> set=goods.getImgsSet();
				Iterator<Imgs> iter=set.iterator();
				for(ItemImg img:imgs)
				{
					boolean has=false;
					Imgs myImg=new Imgs();
					myImg.setImg_url(img.getUrl());
					myImg.setImg_id(img.getId());
					myImg.setGoods(goods);
					while(iter.hasNext())
					{
						if(iter.next().getImg_url().equals(img.getUrl()))
						{
							has=true;
						}
					
					}
					if(!has)
					{
						goods.addImgs(myImg);
					}
				}
			

			}
			
			
			if(dao.get("num_iid", item.getNumIid())!=null)
			dao.update(goods);
			else
			{
			dao.save(goods);
			}
		}
	}
	
	
	public void deleteTaoBaoGoods(Goods goods)
	{
		GrabTaoBao taobao=new GrabTaoBao();
		if(!taobao.isExists(goods.getTb_url()))
		{
			dao.delete(goods);
		}
	}

	public Double getGoodCurrPrice(String url) {
		InfoGrab shop=ShopFactory.instance(url);
		if(shop==null)
		{
			return null;
		}
		return shop.getPrice(url);
	}
	
	public static void main(String[] args) 
	{
		
	}

}
